/**
 * request.js 统一拦截请求文件
 */

import Vue from 'vue';
import axios from 'axios';
import {
	getToken,
	removeToken
} from './author.js';
import option from '../Config';
const { baseUrl, timeout } = option;
let service = axios.create({
	baseURL: baseUrl,
	timeout
});

/**
 * 拦截请求 并且配置token
 */
service.interceptors.request.use(
	config => {
		if (getToken)
			config.headers['Authorization'] = 'Bear' + getToken();
		return config;
	}, error => {
		return Promise.reject(error);
	});

/**
 * 拦截响应 对response 响应数据包进行第一次处理
 */
service.interceptors.response.use(res => {
	let {
		code,
		msg,
		status
	} = res.data;
	if (code == 200 && status == 'success') {
		return res.data;
	} else {
		return Promise.reject(res);

	}

}, error => {
	return Promise.reject(error);
});

/**
 * 对微信小程序、APP、H5进行axios请求进行适配
 * @param {Object} config 
 * @returns 
 */
axios.defaults.adapter = function (config) {
	return new Promise((resolve, reject) => {
		var settle = require('axios/lib/core/settle');
		var buildURL = require('axios/lib/helpers/buildURL');
		uni.request({
			method: config.method.toUpperCase(),
			url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
			header: config.headers,
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: function complete(response) {
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				};
				settle(resolve, reject, response);
			}
		})
	})
}

export default service;
